package com.example.isoftlangchainai.rag.utils;

import com.example.isoftlangchainai.rag.naive.NaiveRagAssistant;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 * @Description: Utils工具类 1.startAPP，用户和系统输入交互
 * @Date :2025/7/16 15:11
 * @Author :chenjun
 */
public class Utils {

    /**
     * [描述]:startAPP，用户和系统输入交互
     */
    public static void startConversationWith(NaiveRagAssistant assistant) {
        Logger log = LoggerFactory.getLogger(NaiveRagAssistant.class);
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                log.info("==================================================");
                log.info("User: ");
                String userQuery = scanner.nextLine();
                log.info("==================================================");

                if ("exit".equalsIgnoreCase(userQuery)) {
                    break;
                }
                String agentAnswer = assistant.answer(userQuery);
                log.info("==================================================");
                log.info("Assistant: " + agentAnswer);
            }
        }
    }

    /**
     * [描述]:startAPP，用户和系统输入交互: 验证嵌入embedding向量相似性搜索与向量内容检索器ContentRetriever结果是否匹配
     * 用户问题：你喜欢的运动是什么?
     */
    public static void startConversationWithPgVector(NaiveRagAssistant assistant, EmbeddingStore<TextSegment> embeddingStore) {
        Logger log = LoggerFactory.getLogger(NaiveRagAssistant.class);
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                log.info("==================================================");
                log.info("User: ");
                String userQuery = scanner.nextLine();
                log.info("==================================================");

                if ("exit".equalsIgnoreCase(userQuery)) {
                    break;
                }
                PgVectorStoreUtils.similarityQuery(userQuery, embeddingStore);
                String agentAnswer = assistant.answer(userQuery);
                log.info("==================================================");
                log.info("Assistant: " + agentAnswer);
            }
        }
    }

    public static Path toPath(String relativePath) {
        try {
            URL fileUrl = Utils.class.getClassLoader().getResource(relativePath);
            return Paths.get(fileUrl.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

}
